package com.rbs.dao.Impl;

import com.rbs.dao.UserDao;
import com.rbs.entity.User;
import com.rbs.util.JDBCUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class UserDaoImpl implements UserDao {
    @Override
    public User selectUserByUsernameAndPassword(String username, String password) {
        Connection conn = null;
        PreparedStatement psmt = null;
        ResultSet rs = null;
        User user = null;
        try {
            //获取连接
            conn = JDBCUtils.getConn();
            //创建preparedStatement
            String sql = "select * from t_user where username = ? and password = ?";
            psmt = conn.prepareStatement(sql);
            //为占位符赋值
            psmt.setString(1,username);
            psmt.setString(2,password);
            //执行sql语句
            rs = psmt.executeQuery();
            //处理结果集
            while (rs.next()){
                user = new User();
                user.setUid(rs.getInt("uid"));
                user.setUsername(rs.getString("username"));
                user.setPassword(rs.getString("password"));
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return user;
    }

    @Override
    public int insertUser(User user) {
        Connection conn = null;
        PreparedStatement psmt = null;
        int i = 0;
        try {
            conn = JDBCUtils.getConn();
            //创建PreparedStatement
            String sql = "insert into t_user(username,password) values(?,?)";
            psmt = conn.prepareStatement(sql);
            //为占位符赋值
            psmt.setString(1,user.getUsername());
            psmt.setString(2,user.getPassword());
            //执行sql语句
            i = psmt.executeUpdate();
        }catch (Exception e){
            e.printStackTrace();
        }
        return i;
    }
}
